package com.lagou.edu.service.impl;

import com.lagou.edu.dao.LagouTokenDao;
import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.service.LagouTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class LagouTokenServiceImpl implements LagouTokenService {

    @Autowired
    private LagouTokenDao tokenDao;

    /**
     * 保存发送的验证码
     *
     * @param token
     * @return
     */
    @Override
    public Boolean saveToken(LagouToken token) {
        LagouToken result = tokenDao.save(token);
        return result.getId() != 0;
    }

    /**
     * 通过token获取
     *
     * @param token
     * @return
     */
    @Override
    public LagouToken findOne(String token) {
        LagouToken lagouToken = LagouToken.builder().token(token).build();

        Example<? extends LagouToken> example = Example.of(lagouToken);
        Optional<? extends LagouToken> tokenOptional = tokenDao.findOne(example);
        if (tokenOptional.isPresent()) {
            return tokenOptional.get();
        }
        return null;
    }

    /**
     * 通过email获取token
     *
     * @param email
     * @return
     */
    @Override
    public LagouToken findOneByEmail(String email) {
        LagouToken lagouToken = LagouToken.builder().email(email).build();

        Example<? extends LagouToken> example = Example.of(lagouToken);
        Optional<? extends LagouToken> tokenOptional = tokenDao.findOne(example);
        if (tokenOptional.isPresent()) {
            return tokenOptional.get();
        }
        return null;
    }
}
